<template>
  <div class="login-container">
    <el-form :model="form" :rules="rules" @submit.prevent="handleLogin">
      <el-form-item prop="userName">
        <el-input 
          v-model="form.userName" 
          placeholder="请输入用户名"
          :prefix-icon="User"
          clearable
        />
      </el-form-item>
      <el-form-item prop="userPassword">
        <el-input
          v-model="form.userPassword"
          type="password"
          placeholder="请输入密码"
          show-password
          :prefix-icon="Lock"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          style="width: 100%"
        >
          立即登录
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="default"
          style="width: 100%; margin-top: 10px"
          @click="$router.push({ name: 'profile.register' })"
        >
          注册账号
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { Lock, User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { setToken } from '@/utils/storage';
import api from '@/api';

const router = useRouter();
const form = ref({
  userName: '',
  userPassword: ''
});
const loading = ref(false);

const handleLogin = async () => {
  try {
    loading.value = true;
    const { data } = await api.post('/user/session', form.value);
    setToken(data);
    ElMessage.success('登录成功');
    router.replace('/');
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败');
  } finally {
    loading.value = false;
  }
};

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
</script>